package com.wyd.rocketmq.test;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

//消费者，接收消息
public class Consumer1 {
    public static void main(String[] args) throws Exception {
        //1 创建消费者对象
        DefaultMQPushConsumer consumer=new DefaultMQPushConsumer("group1");
        //2 指定nameserver地址，连接nameserver
        consumer.setNamesrvAddr("120.24.68.195:9876");
        //3 指定接收哪个主题哪个标题的消息,参数1：表示主题，和生产者端保持一致。参数2：表示标题，*表示任意标题
        consumer.subscribe("topic2","*");
        //设置接收消息模式
        //MessageModel.CLUSTERING：表示负载均衡模式，也是默认的模式
        //consumer.setMessageModel(MessageModel.CLUSTERING);
        //MessageModel.BROADCASTING:表示广播模式，每个消费者都可以接收到所有消息
        consumer.setMessageModel(MessageModel.CLUSTERING);

        //4 设置监听，接收消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                                                            ConsumeConcurrentlyContext context) {
                //遍历msgs集合，打印接收到的消息
                msgs.stream().forEach(messageExt -> System.out.println("接收的消息："+new String(messageExt.getBody())));

                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        //5 启动接收消息的服务器
        consumer.start();
        System.out.println("接收消息的服务器已经启动，准备接收消息了...");
    }
}